$(document).ready(function(){
    // Set autocomplete for ward input
    setAutoComplete2("wardNameTxt", "../Patient/getWardFromDistrictAjax?set_ajax_view&part=","district_id","districtLbx");
    // Set autocomplete for hospital input
    setAutoComplete("registeredHospitalTxt", "../Patient/getHospitalSuggestionAjax?set_ajax_view&part=");
    // Enable medical insurance info only if medical insurance number provided
    if ($.trim($("input#insuranceCodeTxt").val()).length == 0 ) {
            $('input#expired_yyyy').val('');
            $('input#expired_yyyy').attr('readonly', 'readonly');
            $('input#expired_yyyy').css('border-color', '#DDD');
            $('input#expired_mm').val('');
            $('input#expired_mm').attr('readonly', 'readonly');
            $('input#expired_mm').css('border-color', '#DDD');
            $('input#expired_dd').val('');
            $('input#expired_dd').attr('readonly', 'readonly');
            $('input#expired_dd').css('border-color', '#DDD');          
        
            $('select#insuranceTypeLbx').attr('disabled', 'disabled');
            
            $('#registeredHospitalTxt').attr('readonly', 'readonly').css('border-color', '#DDD');
    } 
       
    // Province changed
    $('select#provinceLbx').change( function() {
        provinceChange('provinceLbx', 'districtLbx', 'wardNameTxt');       
    });    
    // Working province changed
    $('select#workingProvinceLbx').change(function(){
        provinceChange('workingProvinceLbx', 'workingDistrictLbx');       
    });

    // Validate patient's birthday
    $('input#DOB_yyyy').blur(function() {
        checkBirthday($(this),$('#DOB_mm'),$('#DOB_dd'));
    });
    $('input#DOB_mm').blur(function(){
        checkMonth($(this),false,'','statusMessage');
    });   
    $('input#DOB_dd').blur(function(){
        checkDay($(this),false,'','statusMessage');
    });
    $('input#personAgeTxt').change(function() {       
        checkAge($(this));
    });

    // Validate phone number
    $('#personPhoneNumberTxt').blur(function(){
    	validatePhoneNumber('personPhoneNumberTxt');
    });

    $('#patientRelativeNumberTxt').blur(function(){
        validatePhoneNumber('patientRelativeNumberTxt');
    });
    
 // Auto fill information if aid-giver is a relative of patient
    $('#aiderNameTxt').blur(function(){
        if($('#isPtnRelativeChk').attr('checked'))
        	$('#patientRelativeNameTxt').val($('#aiderNameTxt').val());
    });
    
    $('#aiderPhoneTxt').blur(function(){
        validatePhoneNumber('aiderPhoneTxt');
        if($('#isPtnRelativeChk').attr('checked'))
        	$('#patientRelativeNumberTxt').val($('#aiderPhoneTxt').val());
    });
    
    $('#aiderAddressTxt').blur(function(){
        if($('#isPtnRelativeChk').attr('checked'))
        	$('#patientRelativeAddress').val($('#aiderAddressTxt').val());
    });

    $('#isPtnRelativeChk').bind('change', function(){
    	fillRelativeInfo();
    });
    
    // Enable medical insurance info only if medical insurance number provided 
    $('input#insuranceCodeTxt').bind("click keydown blur", function() {
        if ($.trim($(this).val()).length > 0 ) { 
            $('input#expired_yyyy').removeAttr('readonly');
            $('input#expired_yyyy').css("border-color", "#AAA");
            $('input#expired_mm').removeAttr('readonly');
            $('input#expired_mm').css("border-color", "#AAA");
            $('input#expired_dd').removeAttr('readonly');
            $('input#expired_dd').css("border-color", "#AAA");
            
            $('select#insuranceTypeLbx').removeAttr('disabled');
            
            $('#registeredHospitalTxt').removeAttr('readonly').css("border-color", "#AAA"); 
        } else { 
            $('input#expired_yyyy').val('');
            $('input#expired_yyyy').attr('readonly', 'readonly');
            $('input#expired_yyyy').css('border-color', '#DDD');
            $('input#expired_mm').val('');
            $('input#expired_mm').attr('readonly', 'readonly');
            $('input#expired_mm').css('border-color', '#DDD');
            $('input#expired_dd').val('');
            $('input#expired_dd').attr('readonly', 'readonly');
            $('input#expired_dd').css('border-color', '#DDD');
            
            $('select#insuranceTypeLbx').attr('disabled', 'disabled');
            
            $('#registeredHospitalTxt').val('').attr('readonly', 'readonly').css('border-color', '#DDD');
        }
    });
    
    // Validate insurance information
    $('input#expired_yyyy').blur(function() {
        checkInsuranceExpireDate($(this),$('#expired_mm'), $('#expired_dd'));
    });
    $('input#insuranceCodeTxt').blur(function() {
        checkInsuranceCode($(this));
    });
    
    // Validate email address
    $('input#personEmailTxt').blur(function() {
        checkEmail($(this), _("Invalid email"), 'statusMessage', '#AAA');
    });
    
});

function saveEmergencyInfo() {
	if(!validatePhoneNumber('aiderPhoneTxt')){
		return;
	}
	var submitData = $('#emergencyInfoFormId').formSerialize();
	
	$.ajax ({
		type:    "POST",
		url:	 "../EmerReception/saveEmerInfoAjax?set_ajax_view",
		data:	 submitData,
		dataType: "json",
		beforeSend: function() {			
			$('#saveReceptionInfoBtn').attr('disabled', 'disabled');
			$("#loaderDiv").show();
		},
		complete: function() {
			$("#loaderDiv").hide();
			$('#saveReceptionInfoBtn').removeAttr('disabled');
		},
		success: function(data) {
			$('#msgSavingStatus').text(_("Saving succeed")).css('color', 'green').show().hide('5000');
			// Fix 926: [Emer]  Check-in dept: update patient's name in common info bar
			$('span#patientName').text(data.patientName);
		}
	});
	
}

function provinceChange(provinceId, districtId, wardId) {
    $.ajax ({
        type:    "GET",
        url:      "../Patient/getDistrictFromProvinceAjax?set_ajax_view",
        data:     "provice_id=" + $('#' + provinceId).val(),
        dataType: "json",
        success:    function(data) {
            if(data.districtList.length > 0){
                $('#' + districtId).html(data.districtList);
            }else{
                var option  =   "<option value='0' label='- " + _('District') + " -'>- "  + _('District') + " -</option>";
                $('#' + districtId).html(option);
            }
			if(wardId != null && wardId != ''){
				districtChange(districtId, wardId);
			}
        }
    });
}

function districtChange(districtId, wardId){
	$.ajax ({
		type:    "GET",
		url:	  "../Patient/ListWardFromDistrictAjax?set_ajax_view",
		data:	  "district_id=" + $('#' + districtId).val(),
		dataType: "json",
		success:	function(data) {
			if(data.wardList.length > 0){
				$('#' + wardId).html(data.wardList);
			}else{
				var option = "<option value='0' label='- " + _('Ward') + " -'>- " + _('Ward') + " -</option>";
				$('#' + wardId).html(option);
			}
		}
	});
}


function checkBirthday(objYear, objMonth, objDay) {
        var res     =   checkDate(objYear, objMonth, objDay, false, _('Empty date of birth'), 'statusMessage', true);
        if(!res){
            return false;
        }
        $('input#personAgeTxt').css("border-color", "#AAA");
        getAge('DOB_yyyy','personAgeTxt');
        return true;    
}

function checkAge(obj) {
    if (obj.val().length > 0 && !obj.val().match(/^[0-9]+$/)) {
        obj.css("border-color", "red");
        obj.focus();
        $('span#statusMessage').text(_("Invalid age")).show();
    } else if (obj.val().length > 0) {
        obj.css("border-color", "#AAA");
        $('input#DOB_yyyy').css("border-color", "#AAA");
        $('input#DOB_mm').css("border-color", "#AAA");
        $('input#DOB_dd').css("border-color", "#AAA");
        $('span#statusMessage').text('');
        getBirthday('personAgeTxt','DOB_yyyy');
    } else {
        obj.css("border-color", "#AAA");
        $('span#statusMessage').hide();
    }
}

function checkInsuranceIssueDate(objYear, objMonth, objDay) {
    if ($.trim($('input#insuranceCodeTxt').val()).length > 0) {
        return checkFullDate(objYear, objMonth, objDay, true,  _('Empty issue date'), 'statusMessage', true);
    }
    return true;
}

function checkInsuranceExpireDate(objYear, objMonth, objDay) {
    if ($.trim($('input#insuranceCodeTxt').val()).length > 0) {
        var res = checkFullDate(objYear, objMonth, objDay, true, _('Empty expiry date'), 'statusMessage', false);
        if (res == false) {
            return false;
        } 
        var expiredDate =   $.trim(objDay.val()) + "/" + $.trim(objMonth.val()) + "/" + $.trim(objYear.val());
        var result = compareDate(expiredDate, "today");
        if (result == "ltToday") {
            objYear.css("border-color", "red");
            objMonth.css("border-color", "red");
            objDay.css("border-color", "red");
            $('span#statusMessage').text(_('Expiry date is less than current date')).show();
            return false;
        }
    }
    if(!objYear.attr('readonly')){
        objYear.css("border-color", "#AAA");
        objMonth.css("border-color", "#AAA");
        objDay.css("border-color", "#AAA");
    }
    $('span#statusMessage').text('').hide();
    return true;
}

function saveRegistrationInfo() {
    if(!isReadyToSubmit()){
        $('span#msgSavingStatus').css('color', 'red').text(_('Fail! Please check the required fields')).show();
        setTimeout("clearText('msgSavingStatus')", 10000);        
        return;
    }
    else{
        $('span#msgSavingStatus').css('color', 'green').text('');
        showLoader(true);
    }
    var submitData = $('#emerReceptionFrm').formSerialize();
    $.ajax ({
        type:    "POST",
        url:     "../EmerReception/saveRegistrationInfo?set_ajax_view",
        data:    submitData,
        dataType: "html",
        beforeSend: function() {            
           
        },
        complete: function() {
            
        },
        success: function(data) {
            $('span#msgSavingStatus').css('color', 'green').text(_('Save successful')).show();
            showLoader(false);
            $('#receptionIdHdn').val(data.receptionId);
            setTimeout("clearText('msgSavingStatus')", 10000);
            $('#body').html(data);
        }
    });
}

function checkInsuranceType(obj) {
    if ($.trim($('input#insuranceCodeTxt').val()).length > 0) {        
        if (!(obj.val() == 'required' || obj.val() == 'volunteered')) {
            obj.css("border-color", "red");
            $('span#statusMessage').text(_("Not yet select insurance type")).show();
            return false;
        }
    }
    obj.css("border-color", "#AAA");
    $('span#statusMessage').text("").hide();
    return true;
}

function checkInsuranceCode(obj) {
    var code = obj.val();
    if ($.trim(code).length > 0) {
        if (!code.match(/^[0-9A-Za-z]+$/)) {
            obj.css("border-color", "red");
            $('span#statusMessage').text(_("Invalid insurance number. Only accept alphanumberic characters")).show();
            return false;
        } else {            
            obj.css("border-color", "#AAA");
            $('span#statusMessage').text("").hide();
            return true;
        }
    }
    return true;
}

function isReadyToSubmitEmergencyInfo() {
	if(!checkTimeCheckIn()){
        return false;
    }
    if (!checkSelectGender()) {
        return false;
    }
    return true;
}

function isReadyToSubmitDemographicsInfo() {
	if (!checkBirthday($('input#DOB_yyyy'),$('input#DOB_mm'), $('input#DOB_dd'))) {
        return false;
    }
    if (!checkEmail($('input#personEmailTxt'), _("Invalid email"), 'statusMessage', '#AAA')) {
        return false;
    }   
    if (!checkInsuranceCode($('input#insuranceCodeTxt'))) {
        return false;
    }
    if (!checkInsuranceType($('select#insuranceTypeLbx'))) {
        return false;
    }    
    if (!checkInsuranceExpireDate($('#expired_yyyy'),$('#expired_mm'), $('#expired_dd'))) {
        return false;
    }       
    
    return true;
}

function isReadyToSubmit() {
    
    var tmp = isReadyToSubmitEmergencyInfo();
    if (!tmp) return tmp;
    
    var tmp = isReadyToSubmitDemographicsInfo();
    if (!tmp) return tmp;
    return true;
}

function checkSelectGender() {
    if ($('#genderMaleRdb').is(':checked') || $('#genderFemaleRdb').is(':checked')) {
        $('span#statusMessage').text("").hide();
        return true;
    }
    $('span#statusMessage').text(_("Not yet select gender")).show();
    return false;
}

function checkTimeCheckIn(){
    var res =   checkFullDate($('#checkIn_yyyy'), $('#checkIn_mm'), $('#checkIn_dd'), true,  _('Empty check-in date'), 'statusMessage', true);
    if(!res){
        return false;
    }
    res = checkHour($('#checkInTimeTxt'), true, _('Invalid time'), 'statusMessage');
    if(!res){
        return false;
    }
    return true;
}

function showLoader(show){
    if(show){
       $('#actionButtonDiv').hide(); 
       $('#loaderDiv').show();
    }  else {
        $('#actionButtonDiv').show(); 
        $('#loaderDiv').hide();
    }
}

function clearText(id){
    $('#' + id).text('');
}

function fillRelativeInfo(){
	if($('#isPtnRelativeChk').attr('checked')){
		$('#patientRelativeNameTxt').val($('#aiderNameTxt').val());
		$('#patientRelativeNumberTxt').val($('#aiderPhoneTxt').val());
		$('#patientRelativeAddress').val($('#aiderAddressTxt').val());
	}
	else{
		$('#patientRelativeNameTxt').val('');
		$('#patientRelativeNumberTxt').val('');
		$('#patientRelativeAddress').val('');
	}
}

function validatePhoneNumber(phoneId){
	return checkNumber($('#' + phoneId), _("Invalid phone number"), 'statusMessage', '#AAA');	
}

function autoTab(thisElem, maxLength, nextElem){
	if(thisElem.value.length == maxLength){
		thisElem.blur();
		$('#' + nextElem).focus();
	}
}

function checkAllergy(){
	if($('#allergyChk').attr('checked')){
		$('#generalAllergyTxt').removeAttr('disabled');
		$('#drugAllergyTxt').removeAttr('disabled');
	}
	else{
		$('#generalAllergyTxt').val('');
		$('#generalAllergyTxt').attr('disabled', 'disabled');
		$('#drugAllergyTxt').val('');
		$('#drugAllergyTxt').attr('disabled', 'disabled');
	}
}
